package com.xinenhua.businessserver.house;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.kennyc.view.MultiStateView;
import com.oasis.oasislib.base.BaseFragmentActivity;
import com.oasis.oasislib.utils.LogUtil;
import com.oasis.oasislib.view.XListView;
import com.xinenhua.businessserver.Const;
import com.xinenhua.businessserver.R;
import com.xinenhua.businessserver.http.BaseHttp;
import com.xinenhua.businessserver.login.pojo.User;

import org.apache.commons.lang3.StringUtils;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 虚拟房源列表
 */
@ContentView(R.layout.houselist)
public class FicHouseList extends BaseFragmentActivity implements XListView.XListViewListener{

    @ViewInject(R.id.spinner)
    MaterialSpinner spinner;

    @ViewInject(R.id.spinner1)
    MaterialSpinner spinner1;

    @ViewInject(R.id.multiStateView)
    MultiStateView multiStateView ;

    @ViewInject(R.id.xlist_campaign)
    XListView xListView ;

    ArrayList<ListPojo> list = new ArrayList<>() ;
    private boolean hasMoreData = true ;
    private int pageIndex = 1 ;

    ListAdapter adapter;

    @ViewInject(R.id.te3xtView5)
    EditText search ;


    //项目选择列表
    List<SelectFilter> projectPojoList = new ArrayList<>();
    SelectFilter currentProjectPojo = null;

    //房源类型
    List<SelectFilter> houseType = new ArrayList<>();
    SelectFilter cuttentHouseType = null;

    String keyword = "";

    User user ;

    @Override
    protected void start() {

        super.start();
        StatusBarCompat.setStatusBarColor(FicHouseList.this, getResources().getColor(R.color.app_green));
        actionBar.hide();

        user = Const.getUser();

        findViewById(R.id.warpper_message).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        multiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
        xListView.setPullLoadEnable(true);
        xListView.setPullRefreshEnable(true);
        xListView.setHeaderProgressDrawable(ContextCompat.getDrawable(FicHouseList.this,R.mipmap.default_ptr_rotate));
        xListView.setRefreshTime();
        xListView.setPULL_LOAD_MORE_DELTA(60);
        xListView.setSCROLL_DURATION(400);
        xListView.setOFFSET_RADIO(3.0f);
        xListView.setXListViewListener(this);

        adapter = new ListAdapter(FicHouseList.this) ;
        adapter.setList(list);
        xListView.setAdapter(adapter);
        xListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //跳转到实体房源详情
                Intent openWelcomeActivityIntent=new Intent();
                Bundle bundle=new Bundle();
                bundle.putString("id",String.valueOf(list.get(position-1).getId()));

                openWelcomeActivityIntent.putExtras(bundle);
                openWelcomeActivityIntent.setClass(FicHouseList.this, HouseDetail.class);
                startActivity(openWelcomeActivityIntent);


            }
        });

        search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId== EditorInfo.IME_ACTION_SEARCH){

                    String key = v.getText().toString();
                    LogUtil.e(TAG,key);
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

                    if(StringUtils.isBlank(key)){

                    }else {
                        //ToastUtils.shortToast(context,key);
                        keyword = key;
                        onRefresh();
                    }
                    return true;
                }
                return false;
            }
        });

        //发生错误重试
        multiStateView.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.retry).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                multiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
                onRefresh();
            }
        });

        //获取项目基础数据
        getProject();

    }

    @Override
    public void onRefresh() {
        list.clear();
        pageIndex = 1 ;
        multiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
        adapter.notifyDataSetChanged();
        getData();
    }

    @Override
    public void onLoadMore() {
        if (hasMoreData) {
            getData() ;
        }else {
            xListView.hideFooter();
        }
    }

    private void getData() {
        HashMap<String,String> map = new HashMap<>() ;
        map.put("page",String.valueOf(pageIndex));
        map.put("build_id",currentProjectPojo.getId());
        map.put("fictitious_status",cuttentHouseType.getId());//虚拟状态（0：空置1：已注册3：将到期 为空显示全部）
        map.put("keyword",keyword);
        map.put("list_rows",Const.list_rows+"");
        map.put("member_id",user.getAdmin_id()+"");


        LogUtil.e(TAG,"search---page--"+String.valueOf(pageIndex));
        LogUtil.e(TAG,"search---build_id--"+currentProjectPojo.getId());
        LogUtil.e(TAG,"search---entity_status--"+cuttentHouseType.getId());
        LogUtil.e(TAG,"search---keyword--"+keyword);
        LogUtil.e(TAG,"search---list_rows--"+Const.list_rows+"");


        Call call = BaseHttp.getCallWithUrlAndData(Const.adminhousefictitious,map);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("Fail");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String rr = new String(response.body().string());
                System.out.println(rr);
                int result = BaseHttp.preResult(rr);
                if(result==BaseHttp.DATA_OK){
                    String s = BaseHttp.getJsonDataAsString(rr);

                    final int total = BaseHttp.getJsonDataAsInt(s,"total") ;
                    int per_page = BaseHttp.getJsonDataAsInt(s,"per_page") ;
                    final int current_page = BaseHttp.getJsonDataAsInt(s,"current_page") ;
                    int last_page = BaseHttp.getJsonDataAsInt(s,"last_page") ;

                    String son = BaseHttp.getJsonDataAsString(s);

                    Gson gson = new Gson();
                    Type listType = new TypeToken<List<ListPojo>>(){}.getType();
                    List<ListPojo> projectList = gson.fromJson(son, listType);

                    list.addAll(projectList);

                    //处理加载数据后 各种控件的状态 规范
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(total==0){
                                multiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                            }else {
                                adapter.notifyDataSetChanged();
                                multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);

                                xListView.setRefreshTime();
                                xListView.stopLoadMore();
                                xListView.stopRefresh();

                                if(list.size()<total){
                                    hasMoreData = true ;
                                    pageIndex = current_page+1 ;
                                }else {
                                    hasMoreData = false ;
                                }

                                if (hasMoreData) {
                                    xListView.showFooter();
                                } else {
                                    xListView.hideFooter();
                                }
                            }
                        }
                    });
                }else {
                    showMsg(BaseHttp.getJsonMsg(rr));
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                            multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);

                            xListView.setRefreshTime();
                            xListView.stopLoadMore();
                            xListView.stopRefresh();
                        }
                    });
                }

            }
        });
    }

    //得到各个项目
    public void getProject(){

        Call call = BaseHttp.getCallWithUrlAndData(Const.adminfilte,null);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("Fail");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String rr = new String(response.body().string());
                System.out.println(rr);
                int result = BaseHttp.preResult(rr);
                if(result==BaseHttp.DATA_OK){
                    String s = BaseHttp.getJsonDataAsString(rr);
                    System.out.println("String--"+s);

                    String column1 = BaseHttp.getJsonDataAsString(s,"column1") ;
                    String entity = BaseHttp.getJsonDataAsString(s,"entity") ;
                    String fictitious = BaseHttp.getJsonDataAsString(s,"fictitious") ;

                    Gson gson = new Gson();
                    Type listType = new TypeToken<List<SelectFilter>>(){}.getType();
                    final List<SelectFilter> column1list = gson.fromJson(column1, listType);

                   /* Type listType1 = new TypeToken<List<SelectFilter>>(){}.getType();
                    final List<SelectFilter> entitylist = gson.fromJson(entity, listType1);*/

                    Type listType2 = new TypeToken<List<SelectFilter>>(){}.getType();
                    final List<SelectFilter> fictitiouslist = gson.fromJson(fictitious, listType2);


                    //初始化筛选数据

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            //项目
                            projectPojoList = column1list;
                            currentProjectPojo = column1list.get(0);

                            spinner.setItems(projectPojoList);
                            spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<SelectFilter>() {

                                @Override public void onItemSelected(MaterialSpinner view, int position, long id, SelectFilter item) {
                                    currentProjectPojo = item;
                                    onRefresh();
                                }
                            });

                            //房源状态
                            houseType = fictitiouslist;
                            cuttentHouseType = fictitiouslist.get(0);

                            spinner1.setItems(houseType);
                            spinner1.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<SelectFilter>() {

                                @Override public void onItemSelected(MaterialSpinner view, int position, long id, SelectFilter item) {
                                    //ToastUtils.shortToast(context,item.mDes);
                                    cuttentHouseType = item;
                                    onRefresh();
                                }
                            });

                            //获取数据
                            getData();
                        }
                    });


                }else {
                    showMsg(BaseHttp.getJsonMsg(rr));
                }

            }
        });


       /* Call call = BaseHttp.getCallWithUrlAndData(Const.adminproject,null);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtils.shortToast(context,"获取基础数据失败 请重试");
                finish();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String rr = new String(response.body().string());
                LogUtil.e(TAG,"getProject----"+rr);
                int result = BaseHttp.preResult(rr);
                if(result==BaseHttp.DATA_OK){
                    String s = BaseHttp.getJsonDataAsString(rr);
                    Gson gson = new Gson();
                    Type listType = new TypeToken<List<ProjectPojo>>(){}.getType();
                    List<ProjectPojo> projectList = gson.fromJson(s, listType);

                    ProjectPojo first = new ProjectPojo();
                    first.setId("");
                    first.setName("全部");

                    projectPojoList.add(first) ;
                    projectPojoList.addAll(projectList);

                    //初始化 项目 筛选条件
                    spinner.setItems(projectPojoList);
                    spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<ProjectPojo>() {

                        @Override public void onItemSelected(MaterialSpinner view, int position, long id, ProjectPojo item) {
                            //ToastUtils.shortToast(context,item);
                            currentProjectPojo = item;
                            onRefresh();
                        }
                    });
                }else {
                    ToastUtils.shortToast(context,BaseHttp.getJsonMsg(rr));
                    finish();
                }

            }
        });*/

    }
}
